import axios from "axios";
import Cookies from "js-cookie";
import errorCodes from "@/utils/errorCodes";
import { ElMessage } from "element-plus";

const request = axios.create({
    baseURL: process.env.VUE_APP_BASE_URL,
    timeout: 10000
})

//添加请求拦截器
request.interceptors.request.use(
    config => {
        // 是否需要设置 token
        const saToken = Cookies.get("satoken");
        if (config.headers.isToken && saToken) {
            //将token写入请求头
            config.headers['satoken'] = saToken;
        }
        //发送请求
        return config;
    }, error => {
        console.log(error);
        return Promise.reject(error);
    }
)

//添加响应拦截器
request.interceptors.response.use(
    response => {
        //获取响应状态码,后端返回的数据在response.data中
        const code = response.data.code || 200;
        const msg = errorCodes[code] || response.data.msg || errorCodes['default'];
        //展示请求失败返回信息
        if (code !== 200) {
            ElMessage({ message: msg, type: "error" })
            return Promise.resolve(new Error(msg))
        }
        //响应放行
        return response.data;
    }, error => {
        ElMessage({ message: '系统接口异常', type: "error" })
        return Promise.resolve(new Error(error))
    }
);

export default request;